<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage>
      <div>
        <n-form ref="form"
                :model="searchCondition"
                :show-require-mark="false"
                label-align="right"
                label-placement="left"
                label-width="80px">
          <div>
            <div class="grid md:flex md:flex-wrap md:gap-x-1">
              <n-form-item>
                  <label style="width: 100px;">物流商名称：</label>
                  <n-input v-model:value="searchCondition.name" clearable
                           placeholder="输入物流商名称" style="width: 170px;"/>
              </n-form-item>
              <n-form-item>
                  <n-button style="margin-left: 10px"
                            type="primary"
                            @click="searchByCondition">
                      筛选
                  </n-button>
      </n-form-item>
              <n-form-item>
                <n-button style=" margin-left: 10px"
                          type="error"
                          @click="deleteSelectLogisticsProvider">
                  批量删除
                </n-button>
              </n-form-item>
              <n-form-item>
                  <n-button style="margin-left: 10px" type="primary" @click="showForm = true">
                      添加物流商
                  </n-button>
              </n-form-item>
              <n-form-item>
                  <n-button style="margin-left: 10px" type="primary" @click="exportListInfo">
                      导出
                  </n-button>
              </n-form-item>
            </div>
          </div>
        </n-form>
        <AddLogisticProviderForm
            @update-page="searchByCondition"
            :show="showForm"
            :onClose="handleClose"
        />
        <UpdateLogisticProviderForm
            :option="option"
            @update-page="searchByCondition"
            :show1="showForm1"
            :onClose="handleClose"
            :attribute="currentAttribute"
        />
        <n-data-table
            remote
            :single-line="false"
            ref="table"
            :columns="columns"
            :data="logisticsProviderList"
            :loading="loading"
            :pagination="paginationReactive"
            :row-key="rowKey"
            :scroll-x="900"
            @update:checked-row-keys="handleCheck"
        />
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';

import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import LogisticsActions from './components/logistics-actions.vue';
import AddLogisticProviderForm from './components/logisticsProvider-add.vue'
import UpdateLogisticProviderForm from './components/logisticsProvider-edit.vue'

const showForm = ref(false);
const searchCondition = ref({
  name: ''
})
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const logisticsProviderList = ref([])
const range = ref(null)
const showForm1 = ref(false);
const currentAttribute = ref(null); // 当前编辑的属性
const option = ref([])

const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'id',
    title: '物流商编号',
    width: 100,
  },
  {
        key: 'name',
        title: '物流商名称',
        width: 100,
    },
    {
        key: 'contactName',
        title: '联系人',
        width: 100,
    },
    {
        key: 'contactPhone',
        title: '联系电话',
        width: 100,
    },
    {
        key: 'supportAddress',
        title: '支持配送区域',
        width: 100,
    },
    {
        key: 'supportChannel',
        title: '支持配送方式',
        width: 100,
    },
    {
        key: 'do',
        title: '操作',
        width: 100,
        render(row) {
            return h(
                LogisticsActions,
                {
                    onClickEdit: () => onEditLogisticsProvider(row),
                    onClickDelete: () => onDeleteLogisticsProvider(row),
                }
            );
        }
    },


]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const deleteSelectLogisticsProvider = () => {
  if (checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择物流商！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选物流商？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteLogisticsProviders({ params: { ids } })
        if (res.code === 200) {
          $message.success("删除所选物流商成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选物流商失败！")
      } finally {
        loading.value = false
      }
    },
  })
}
const onEditLogisticsProvider = async (logisticsProvider) => {
  currentAttribute.value = logisticsProvider; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}
const searchByCondition = async () => {
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageLogisticsProvider({
      params: {
        name:searchCondition.value.name,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      logisticsProviderList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询物流商失败！")
  }finally{
    loading.value = false
  }
}
const onDeleteLogisticsProvider = (row) => {
  $dialog.warning({
    title: '警告',
    content: '您确定删除此物流商？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      loading.value = true
      try {
        const res = await api.deleteLogisticsProvider({ id: row.id})
        if (res.code === 200) {
          $message.success("删除物流商成功！")
          await queryByPage()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除物流商失败！")
      } finally {
        loading.value = false
      }
    }
  })
}
const exportListInfo = async () => {
  const res = await api.exportLogisticsProviderList({
    name: searchCondition.value.name,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if (contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else {
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.style.display = 'none'
    const href = window.URL.createObjectURL(blob)
    elink.href = href
    elink.download = fileName
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const queryByPage = async ()=>{
    loading.value = true
    try {
        const res = await api.findPageLogisticsProvider(
            {params:{
                pageNum: paginationReactive.page,
                pageSize: paginationReactive.pageSize,
              }
            })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            logisticsProviderList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: i+1
                }
            })
            $message.success("获取物流商成功！")
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取物流商失败！")
    }finally{
        loading.value = false
    }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
  queryByPage()
})
</script>
<style scoped>
    :deep(.n-data-table-th__title),
    :deep(.n-data-table-td) {
        text-align: center;

    }
    :deep(.n-select) {
        width: 140px !important;
    }

    :deep(.two-line-description) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 控制显示的行数 */
        overflow: hidden;
    }

</style>
